package com.hardware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hardware.common.R;
import com.hardware.dto.ShopDto;
import com.hardware.dto.SupplierDto;
import com.hardware.entity.Category;
import com.hardware.entity.Customer;
import com.hardware.entity.Shop;
import com.hardware.entity.Supplier;
import com.hardware.entity.category.SupplierCategory;
import com.hardware.mapper.CustomerMapper;
import com.hardware.mapper.SupplierMapper;
import com.hardware.service.CustomerService;
import com.hardware.service.SupplierService;
import com.hardware.service.category.SupplierCategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {

    @Autowired
    private SupplierCategoryService supplierCategoryService;
    @Override
    public R<Page> page(int page, int pageSize, String name) {
        /*//构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Supplier> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Supplier::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Supplier::getUpdateTime);
        //执行查询
        page(pageInfo,queryWrapper);

        return R.success(pageInfo);*/

        //构造分页构造器对象
        Page<Supplier> pageInfo = new Page<>(page,pageSize);
        Page<SupplierDto> supplierDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Supplier> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Supplier::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Supplier::getUpdateTime);
        //执行分页查询
        this.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,supplierDtoPage,"records");
        List<Supplier> records = pageInfo.getRecords();
        List<SupplierDto> list = records.stream().map((item) -> {
            SupplierDto supplierDto = new SupplierDto();
            BeanUtils.copyProperties(item,supplierDto);

            //根据id查询分类对象
            SupplierCategory category = supplierCategoryService.getById(item.getCategoryId());

            if(category != null){
                supplierDto.setCategoryName(category.getName());
            }
            return supplierDto;
        }).collect(Collectors.toList());

        supplierDtoPage.setRecords(list);

        return R.success(supplierDtoPage);
    }

}
